#! /usr/bin/python

import re
import os
from optparse import OptionParser
import shutil


parser = OptionParser()

parser.add_option('-r', '--ralf', action='store', dest='ralf', help='Store ralf file')

parser.add_option('-e', '--spec', action='store', dest='spreadsheet', help='Store registers spreadsheet')

parser.add_option('-b', '--bin_dir', action='store', dest='bin_dir', help='please set bin directory')

(options, args) = parser.parse_args()

#bin_dir = options.bin_dir
bin_dir = '/ux/flow/dv'

if options.ralf is None:
	os.system(bin_dir + '/spec2ralf/spec2ralf.py --spec ' + options.spreadsheet + ' --bin_dir ' + bin_dir )
	index_file = open('spec_gen.index')
	ralf_file = index_file.readline()
	index_file.close()
else:
	#Get full ralf file's name with suffix .ralf
	str_list=options.ralf.split('/')
	ralf_file=str_list[-1]

#Get ralf file's name without suffix .ralf
str_list  = ralf_file.split('.')
#ralf_name = str_list[0]
#str_list  = str_list[0].split('_')
top_name  = str_list[0]

print ralf_file


#Generate RAL model from RALF spec
os.system('ralgen -full64 -t ' + top_name + ' ' + ralf_file + ' -uvm -c a -auto_mirror')

#Add comments to RAL model and delete redundant code
processed_ral=open('ral_' + top_name + '_processed.sv', "a")
processed_ral.write('//PLEASE DO NOT MODIFY MANUALLY.'+'\n')
processed_ral.write('//RAL model automatically generated from RALF spec.'+'\n')
processed_ral.write('//Please revise RALF spec to regenerate this RAL model.'+'\n')
processed_ral.write(''+'\n')
processed_ral.write(re.sub(r'import uvm_pkg::\*;', "", open('ral_' + top_name + '.sv').read()))
processed_ral.close()

shutil.move('./ral_' + top_name + '_processed.sv', './' + top_name + '_regs.sv')
os.remove('ral_' + top_name + '.sv')

if options.ralf is None:
	os.remove('spec_gen.index')
	#os.remove(options.spreadsheet +'.index')

print "\nSV file generation done!\n"

